package com.flybutter.usagelab

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import android.content.DialogInterface
import android.content.Intent
import android.app.AppOpsManager
import android.app.SearchManager
import android.content.Context
import android.os.Process
import android.provider.Settings
import android.transition.Explode
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.Window
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.core.util.Pair
import androidx.fragment.app.Fragment
import com.flybutter.usagelab.databinding.ActivityMainBinding
import com.flybutter.usagelab.service.MonitorService
import com.flybutter.usagelab.ui.dashboard.DashboardFragment
import com.flybutter.usagelab.ui.home.HomeFragment
import com.flybutter.usagelab.ui.notifications.NetworkFragment
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.DateValidatorPointBackward
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.tabs.TabLayout

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private var dialog: AlertDialog? = null

    private lateinit var mainTab: TabLayout
    private val map: MutableMap<Int,Fragment> = mutableMapOf()
    val searchHandlers = mutableListOf<(String)->Unit>()
    val datePickerHandlers = mutableListOf<(Pair<Long,Long>)->Unit>()

    private var datePicker: MaterialDatePicker<Pair<Long,Long>>? = null
    private var lastQueryText: String? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS)
        window.enterTransition = Explode().setDuration(300)
        binding = ActivityMainBinding.inflate(layoutInflater)
//        mainTab = binding.mainTab
        setContentView(binding.root)
//        initTab()
//        mainTab.selectTab(mainTab.getTabAt(0))
        startService(Intent(this,MonitorService::class.java))
    }

    fun initTab(){
        mainTab.addTab(mainTab.newTab().setId(R.id.navigation_home).setText("使用统计"))
        mainTab.addTab(mainTab.newTab().setId(R.id.navigation_notifications).setText("网络"))

        val onSelectedListener = object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                if (tab == null)
                    return
                var target = map[tab.id]
                if (target == null){
                    target = when(tab.id){
                        R.id.navigation_home -> HomeFragment()
                        R.id.navigation_dashboard -> NetworkFragment()
                        else -> NetworkFragment()
                    }
                    supportFragmentManager.beginTransaction().apply {
                        map[tab.id] = target
                        add(R.id.fragment_container,target,tab.id.toString())
                        commit()
                    }
                } else {
                    supportFragmentManager.beginTransaction().apply {
                        show(target)
                        commit()
                    }
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                supportFragmentManager.apply {
                    val transaction = beginTransaction()
                    val frg = findFragmentByTag(tab?.id.toString())
                    if (frg != null){
                        transaction.hide(frg)
                    }
                    transaction.commit()
                }
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {}
        }

        mainTab.addOnTabSelectedListener(onSelectedListener)
        onSelectedListener.onTabSelected(mainTab.getTabAt(0))
    }

    override fun onResume() {
        super.onResume()
        requestPermission()
    }

    private fun requestPermission() {
        if (checkPermission()) {
            if (dialog != null) {
                dialog!!.cancel()
            }
            return
        }
        //提示用户授予权限
        dialog = MaterialAlertDialogBuilder(this)
            .setMessage("请授予获取信息权限")
            .setPositiveButton("允许") { dialog: DialogInterface?, which: Int ->
                startActivity(
                    Intent(
                        Settings.ACTION_USAGE_ACCESS_SETTINGS
                    )
                )
            }
            .show()
    }

    fun addOnSearchListener(handler: (String)->Unit){
        searchHandlers.add(handler)
    }

    fun addDateSelectListener(hanlder:(Pair<Long,Long>)->Unit){
        datePickerHandlers.add(hanlder)
    }

    @SuppressLint("ServiceCast")
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.app_menu,menu)
        val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
        val searchView = menu?.findItem(R.id.search)?.actionView as androidx.appcompat.widget.SearchView
        searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
        searchView.isSubmitButtonEnabled = true
        searchView.setOnSearchClickListener {
            Log.d("TEST", "onCreateOptionsMenu: search")
        }
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                lastQueryText = query
                searchHandlers.forEach { it(query?:"") }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if (!lastQueryText.isNullOrBlank() && newText.isNullOrBlank()){
                    searchHandlers.forEach { it("") }
                }
                return true
            }
        })
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.date_range){
            if (datePicker == null){
                datePicker = MaterialDatePicker.Builder.dateRangePicker()
                    .setTitleText("select date range")
                    .setCalendarConstraints(CalendarConstraints.Builder()
                        .setValidator(DateValidatorPointBackward.now())
                        .build())
                    .build()
                datePicker!!.addOnPositiveButtonClickListener { pair->
                    datePickerHandlers.forEach { it(pair) }
                }
            }
            datePicker?.show(supportFragmentManager,"tag")
        }
        return super.onOptionsItemSelected(item)
    }

    private fun checkPermission(): Boolean {
        val appOpsManager = getSystemService(APP_OPS_SERVICE) as AppOpsManager
        val mode = appOpsManager.checkOpNoThrow(
            AppOpsManager.OPSTR_GET_USAGE_STATS,
            Process.myUid(), packageName
        )
        return mode == AppOpsManager.MODE_ALLOWED
    }
}